import {
  CallHandler,
  ExecutionContext,
  Inject,
  Injectable,
  NestInterceptor,
  Logger,
} from '@nestjs/common';
import { Observable, map } from 'rxjs';

@Injectable()
export class ResponseInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    // 解析 ExecutionContext 的数据内容，获取请求体
    const ctx = context.switchToHttp();
    const request = ctx.getRequest();

    // 数据遍历、转换
    return next.handle().pipe(
      map((data) => {
        Logger.log(`
        url: ${request.url}
        参数：${JSON.stringify(
          ['POST', 'PUT'].includes(request.method)
            ? request.body
            : request.query,
        )}
        响应：${JSON.stringify(data)}
      `);

        return {
          code: 200,
          msg: '请求成功',
          data,
        };
      }),
    );
  }
}
